package com.fh.controller.hydropower;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.fh.entity.system.TreeNode;
import com.fh.entity.system.User;
import com.fh.service.building.RecordService;
import com.fh.service.hydropower.HydropowerPriceService;
import com.fh.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.system.Menu;
import com.fh.entity.Page;

/** 
 * 类名称：HydropowerPriceController
 * 创建人：FH 
 * 创建时间：2017-10-16
 */
@Controller
@RequestMapping(value="/hydropowerprice")
public class HydropowerPriceController extends BaseController {
	
	@Resource(name="hydropowerPriceService")
	private HydropowerPriceService hydropowerPriceService;
	@Resource(name = "recordService")
	private RecordService recordService;
	

	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除Hydropower_price");
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			hydropowerPriceService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit() throws Exception{
		logBefore(logger, "修改Hydropower_price");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		hydropowerPriceService.edit(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表Hydropower_price");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = hydropowerPriceService.list(page);	//列出Hydropower_price列表
			mv.setViewName("hydropower/hydropower_price/hydropower_price_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Hydropower_price页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("hydropower/hydropower_price/hydropower_price_edit");
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改Hydropower_price页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = hydropowerPriceService.findById(pd);	//根据ID读取
			mv.setViewName("hydropower/hydropower_price/hydropower_price_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Hydropower_price");
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				hydropowerPriceService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出Hydropower_price到excel");
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("display: inline");	//1
			titles.add("display: inline");	//2
			titles.add("display: inline");	//3
			dataMap.put("titles", titles);
			List<PageData> varOList = hydropowerPriceService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("BUILDING_ID"));	//1
				vpd.put("var2", varOList.get(i).getString("ELETRIC_PRICE"));	//2
				vpd.put("var3", varOList.get(i).getString("WATER_PRICE"));	//3
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}

	/**
	 * 获取水电表价格信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/findhydropowerprice")
	@ResponseBody
	public Object findByPid() {
		logBefore(logger, "获取水电表价格信息");
		PageData pd = new PageData();
		PageData resultPd = new PageData();
		try {
			pd = this.getPageData();
			pd = hydropowerPriceService.findBybuildingId(pd);
			resultPd.put("data",pd);
			resultPd.put("errcode", "00");
			resultPd.put("errmsg", "获取成功");
		} catch (Exception e) {
			resultPd.put("errcode", "01");
			resultPd.put("errmsg", "获取失败");
			logger.error(e.toString(), e);
		}
		return resultPd;
	}

	/**
	 * 新增
	 *
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save() {
		logBefore(logger, "新增");
		PageData pd = new PageData();
		PageData resultPd = new PageData();
		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);
		try {
			pd = this.getPageData();
			if(pd.containsKey("type") && pd.getString("type").equals("b938139a48ed4344a11a7180b48eede6")){
				pd.put("eletricPrice",pd.getString("price"));
			}else {
				pd.put("waterPrice",pd.getString("price"));
			}
			if(pd.containsKey("id") && StringHelper.isNotEmpty(pd.getString("id"))){
				hydropowerPriceService.edit(pd);
			}
			else {
				pd.put("id", this.get32UUID());    //主键
				pd.put("isDel", 0); //是否删除
				pd.put("sort", 0); //排序
				pd.put("createId", this.getSessionUser().getUSER_ID()); //创建时间
				pd.put("createDate", new DateUtil().getTime()); //创建时间
				hydropowerPriceService.save(pd);
			}
			//保存全局记录
			PageData SystemPd = new PageData();
			SystemPd.put("ID", this.get32UUID());//主键
			SystemPd.put("IS_DEL", 0); //是否删除
			SystemPd.put("SORT", 0); //排序
			SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
			SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
			SystemPd.put("DETAILS","修改水电表默认单价");
			SystemPd.put("OPERA_TIME",new DateUtil().getTime());
			SystemPd.put("OPERATOR",user.getNAME());
			SystemPd.put("IP",user.getIP());
			SystemPd.put("OP_PD",pd.toString());
			recordService.SaveSystem(SystemPd);
			resultPd.put("errcode", "00");
			resultPd.put("errmsg", "操作成功");
		} catch (Exception e) {
			resultPd.put("errcode", "01");
			resultPd.put("errmsg", "操作失败");
			logger.error(e.toString(), e);
		}
		return resultPd;
	}
}
